import { Modal, Form, Input, message } from 'antd'
import React, { useState, useEffect, useRef } from'react'
import { projectFlowInsert, projectFlowUpdate} from '@/api/project-flow.js'
import { cloneDeep } from 'lodash'
import { Select } from 'antd'

export const TemplateCategoryModal = (props) => {
  const { initData, onSuccess, onClose } = props
  const formRef = useRef()
  
  const [modalData, setModalData] = useState({
    visible: false,
    confirmLoading: false,
    formData: null
  })

  const [form] = Form.useForm()

  const onEdit = (data) => {
    data = data && data.id ? data : { ...initData, flowName: ''}
    setModalData({
      ...modalData,
      formData: data,
      visible: true
    })
    form.setFieldsValue({
      flowName: data.flowName
    })
  }

  const onOk = () => {
    return onCancel()

    formRef.current.validateFields()
      .then((value) => {
        const submitData = cloneDeep(value)
        let menthod = projectFlowInsert
        if (modalData.formData.id) {
          menthod = projectFlowUpdate
        }
        setModalData({
          ...modalData,
          confirmLoading: true
        })
        menthod({...modalData.formData, ...submitData}).then((res) => {
          onSuccess(res.data)
          onClose()
          message.success('保存成功')
          setModalData({
            ...modalData,
            visible: false,
            confirmLoading: false
          })
        })
      })
  }

  const onCancel = () => {
    setModalData({
      ...modalData,
      visible: false
    })
    onClose()
  }

  useEffect(() => {
    if (initData) {
      onEdit(initData)
    }
  }, [ initData ])

  return <Modal centered title='设置分类' confirmLoading={modalData.confirmLoading} open={modalData.visible} onOk={onOk} onCancel={onCancel}>
  <Form ref={formRef} form={form} layout="vertical" initialValues={modalData.formData}>
    <Form.Item label="分类" name="flowName">
      <Select>
        <Select.Option value="1">分类1</Select.Option>
        <Select.Option value="1">分类2</Select.Option>
      </Select>
    </Form.Item>
  </Form>
</Modal>
}